<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use think\Db;

/**
 * 费用和人次的同比和环比
 *
 * @icon fa fa-circle-o
 */
class Statistica extends Backend
{

    /**
     * Statistica模型对象
     * @var \app\admin\model\pt\Statistica
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\Statistic;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        $yearId = date('Y');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $yearId = date('Y', strtotime($this->request->get('query_date') . "-01"));

            $personYearToYear = $this->personYearToYear($yearId);
            $personPercent = $this->personPercent($yearId);
            
            $result = ['personYearToYear' => $personYearToYear, 'personPercent' => $personPercent];    

            $this->success('获取成功', '', $result);
        } else {
            $personYearToYear = $this->personYearToYear($yearId);
            $personPercent = $this->personPercent($yearId);
        }
        $this->view->assign('personYearToYear', json_encode($personYearToYear));
        $this->view->assign('personPercent', json_encode($personPercent));
        $this->view->assign('query_date', $yearId);
        return $this->view->fetch();
    }

    public function fee()
    {
        $yearId = date('Y');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $yearId = date('Y', strtotime($this->request->get('query_date') . "-01"));

            $personYearToYear = $this->feeYearToYear($yearId);
            $personPercent = $this->feePercent($yearId);
            
            $result = ['personYearToYear' => $personYearToYear, 'personPercent' => $personPercent];    

            $this->success('获取成功', '', $result);
        } else {
            $personYearToYear = $this->feeYearToYear($yearId);
            $personPercent = $this->feePercent($yearId);
        }
        $this->view->assign('personYearToYear', json_encode($personYearToYear));
        $this->view->assign('personPercent', json_encode($personPercent));
        $this->view->assign('query_date', $yearId);
        return $this->view->fetch();
    }

    private function personPercent($yearId)
    {
        $nowYearId = date('Y');
        $curYearId = $yearId;
        // 往前推13个月份
        // 如果是查当年
        $months = [];
        if ($curYearId == $nowYearId) {
            $endMonth = date('Ym');
        } else {
            // 非当年
            $endMonth = date('Ym', strtotime($curYearId . '1201'));
        }
        $endMonth = $endMonth . '01';
        $monthTotal = 13;
        for ($m = 0; $m < $monthTotal; $m++) {
            $monthId = date('Ym', strtotime('-' . $m . ' months', strtotime($endMonth)));
            $months[] = $monthId;
        }

        // 查出总费用
        $list = Db::name('pt_statistic')
          ->where('month_id', 'in', $months)
          ->field('month_id, fee_total as total_fee, person_total as total_person')
          ->order('month_id', 'asc')
          ->select();
        $curData = [];
        foreach ($list as $l) {
            $curData[$l['month_id']]  = [
                'month_id' => $l['month_id'],
                'total_fee' => $l['total_fee'],
                'total_person' => $l['total_person'],
            ];
        }
        /*
        echo "<pre>";
        var_dump($curData);
        echo "</pre>";
         */
        $monthss = [];
        $legend = ['月份', '环比'];
        $curYear = '月份';
        $maxPerson = 0;
        $maxPercent = 0;
        $curPersons = [];
        $percent = [];

        $resData = [];
        $count = count($months) - 1;
        foreach ($months as $key => $m) {
            if ($key != $count) {
                $curPerson = 0;
                $prevPerson = 0;
                if (isset($curData[$m])) {
                    $curPerson = $curData[$m]['total_person'];
                }
                if (isset($curData[$months[$key + 1]])) {
                    $prevPerson = $curData[$months[$key + 1]]['total_person'];
                }
                $per = 0;
                if ($curPerson > 0 && $prevPerson > 0) {
                    $per = round($curPerson / $prevPerson * 100, 2); 
                } else if ($curPerson >0 && $prevPerson == 0){
                    $per = 100;
                }
                // echo $m . '-' . $curPerson . "--". $months[$key + 1] . '-'. $prevPerson . "-" . $percent. "<br />";
                $curPersons[] = $curPerson;
                $percent[] = $per;
                $monthss[] = substr($m, 2, 2) . "/" . substr($m, 4);
            }
        }

        $maxPercent = max($percent);
        $maxPerson = max($curPersons);

        $data['months'] = array_reverse($monthss);
        $data['legend'] = $legend;
        $data['curYear'] = $curYear;
        $data['maxPerson'] = $maxPerson;
        $data['maxPercent'] = $maxPercent;
        $data['curPersons'] = array_reverse($curPersons);
        $data['percent'] = array_reverse($percent);

        return $data;
    }

    private function personYearToYear($yearId)
    {
        $nowYearId = date('Y');
        $curYearId = $yearId;
        $prevYearId = $curYearId - 1;
        $years = $this->getYears($yearId);
        $curMonths = $years[0];
        $prevMonths = $years[1];
        // 查出总费用
        $list = Db::name('pt_statistic')
          ->where('month_id', 'in', $curMonths)
          ->field('month_id, fee_total as total_fee, person_total as total_person')->select();
        $curData = [];
        foreach ($list as $l) {
            $curData[$l['month_id']]  = [
                'month_id' => $l['month_id'],
                'total_fee' => $l['total_fee'],
                'total_person' => $l['total_person'],
            ];
        }

        $list = Db::name('pt_statistic')
          ->where('month_id', 'in', $prevMonths)
          ->field('month_id, fee_total as total_fee, person_total as total_person')->select();
        $prevData = [];
        foreach ($list as $l) {
            $prevData[$l['month_id']]  = [
                'month_id' => $l['month_id'],
                'total_fee' => $l['total_fee'],
                'total_person' => $l['total_person'],
            ];
        }
        // 月份数据
        $months = [];
        foreach ($curMonths as $m) {
            $months[] = date('m月', strtotime($m . '01'));
        }
        // legend
        $legend = [strval($prevYearId), strval($curYearId), '同比'];
        // 
        $prevYear = strval($prevYearId);
        $curYear = strval($curYearId);
        $maxPerson = 0;
        $maxPercent = 0;
        $prevPersons = [];
        $curPersons = [];
        $percent = [];
        foreach ($curMonths as $curMonthId) {
            $month = date('m', strtotime($curMonthId . '01'));
            $prevMonthId = $prevYearId . $month;
            $prevPerson = 0;
            if (isset($prevData[$prevMonthId])) {
                $prevPerson = $prevData[$prevMonthId]['total_person'];
            }
            
            $curPerson = 0;
            if (isset($curData[$curMonthId])) {
                $curPerson = $curData[$curMonthId]['total_person'];
            }
            $prevPersons[] = $prevPerson;
            $curPersons[] = $curPerson;
            $per = 0;
            if ($curPerson>0 && $prevPerson>0) {
                $per = round($curPerson / $prevPerson * 100, 2);
            } else if ($curPerson>0 && $prevPerson == 0) {
                $per = 100;
            }
            $percent[] = $per;
        }
        // 找出人员中的最大值
        $maxPerson = max($prevPersons);
        $max2 = max($curPersons);
        if ($max2 > $maxPerson ) {
            $maxPerson = $max2;
        }
        $maxPerson += 10;
        $maxPercent = max($percent);
        if ($maxPercent < 100) {
            $maxPercent = 100;
        } else {
            $maxPercent += 10;
        }
        
        $data['months'] = $months;
        $data['legend'] = $legend;
        $data['prevYear'] = $prevYear;
        $data['curYear'] = $curYear;
        $data['maxPerson'] = $maxPerson;
        $data['maxPercent'] = $maxPercent;
        $data['prevPersons'] = $prevPersons;
        $data['curPersons'] = $curPersons;
        $data['percent'] = $percent;

        return $data;

    }


    private function feePercent($yearId)
    {
        $nowYearId = date('Y');
        $curYearId = $yearId;
        // 往前推13个月份
        // 如果是查当年
        $months = [];
        if ($curYearId == $nowYearId) {
            $endMonth = date('Ym');
        } else {
            // 非当年
            $endMonth = date('Ym', strtotime($curYearId . '1201'));
        }
        $endMonth = $endMonth . '01';
        $monthTotal = 13;
        for ($m = 0; $m < $monthTotal; $m++) {
            $monthId = date('Ym', strtotime('-' . $m . ' months', strtotime($endMonth)));
            $months[] = $monthId;
        }

        // 查出总费用
        $list = Db::name('pt_statistic')
          ->where('month_id', 'in', $months)
          ->field('month_id, fee_total as total_fee, person_total as total_person')
          ->order('month_id', 'asc')
          ->select();
        $curData = [];
        foreach ($list as $l) {
            $curData[$l['month_id']]  = [
                'month_id' => $l['month_id'],
                'total_fee' => $l['total_fee'],
                'total_person' => $l['total_person'],
            ];
        }
        /*
        echo "<pre>";
        var_dump($curData);
        echo "</pre>";
         */
        $monthss = [];
        $legend = ['月份', '环比'];
        $curYear = '月份';
        $maxPerson = 0;
        $maxPercent = 0;
        $curPersons = [];
        $percent = [];

        $resData = [];
        $count = count($months) - 1;
        foreach ($months as $key => $m) {
            if ($key != $count) {
                $curPerson = 0;
                $prevPerson = 0;
                if (isset($curData[$m])) {
                    $curPerson = $curData[$m]['total_fee'];
                }
                if (isset($curData[$months[$key + 1]])) {
                    $prevPerson = $curData[$months[$key + 1]]['total_fee'];
                }
                $per = 0;
                if ($curPerson > 0 && $prevPerson > 0) {
                    $per = round($curPerson / $prevPerson * 100, 2); 
                } else if ($curPerson >0 && $prevPerson == 0){
                    $per = 100;
                }
                // echo $m . '-' . $curPerson . "--". $months[$key + 1] . '-'. $prevPerson . "-" . $percent. "<br />";
                $curPersons[] = $curPerson;
                $percent[] = $per;
                $monthss[] = substr($m, 2, 2) . "/" . substr($m, 4);
            }
        }

        $maxPercent = max($percent);
        $maxPerson = max($curPersons);

        $data['months'] = array_reverse($monthss);
        $data['legend'] = $legend;
        $data['curYear'] = $curYear;
        $data['maxPerson'] = $maxPerson;
        $data['maxPercent'] = $maxPercent;
        $data['curPersons'] = array_reverse($curPersons);
        $data['percent'] = array_reverse($percent);

        return $data;
    }

    private function feeYearToYear($yearId)
    {
        $nowYearId = date('Y');
        $curYearId = $yearId;
        $prevYearId = $curYearId - 1;
        $years = $this->getYears($yearId);
        $curMonths = $years[0];
        $prevMonths = $years[1];
        // 查出总费用
        $list = Db::name('pt_statistic')
          ->where('month_id', 'in', $curMonths)
          ->field('month_id, fee_total as total_fee, person_total as total_person')->select();
        $curData = [];
        foreach ($list as $l) {
            $curData[$l['month_id']]  = [
                'month_id' => $l['month_id'],
                'total_fee' => $l['total_fee'],
                'total_person' => $l['total_person'],
            ];
        }

        $list = Db::name('pt_statistic')
          ->where('month_id', 'in', $prevMonths)
          ->field('month_id, fee_total as total_fee, person_total as total_person')->select();
        $prevData = [];
        foreach ($list as $l) {
            $prevData[$l['month_id']]  = [
                'month_id' => $l['month_id'],
                'total_fee' => $l['total_fee'],
                'total_person' => $l['total_person'],
            ];
        }
        // 月份数据
        $months = [];
        foreach ($curMonths as $m) {
            $months[] = date('m月', strtotime($m . '01'));
        }
        // legend
        $legend = [strval($prevYearId), strval($curYearId), '同比'];
        // 
        $prevYear = strval($prevYearId);
        $curYear = strval($curYearId);
        $maxPerson = 0;
        $maxPercent = 0;
        $prevPersons = [];
        $curPersons = [];
        $percent = [];
        foreach ($curMonths as $curMonthId) {
            $month = date('m', strtotime($curMonthId . '01'));
            $prevMonthId = $prevYearId . $month;
            $prevPerson = 0;
            if (isset($prevData[$prevMonthId])) {
                $prevPerson = $prevData[$prevMonthId]['total_fee'];
            }
            
            $curPerson = 0;
            if (isset($curData[$curMonthId])) {
                $curPerson = $curData[$curMonthId]['total_fee'];
            }
            $prevPersons[] = $prevPerson;
            $curPersons[] = $curPerson;
            $per = 0;
            if ($curPerson>0 && $prevPerson>0) {
                $per = round($curPerson / $prevPerson * 100, 2);
            } else if ($curPerson>0 && $prevPerson == 0) {
                $per = 100;
            }
            $percent[] = $per;
        }
        // 找出人员中的最大值
        $maxPerson = max($prevPersons);
        $max2 = max($curPersons);
        if ($max2 > $maxPerson ) {
            $maxPerson = $max2;
        }
        $maxPerson += 10;
        $maxPercent = max($percent);
        if ($maxPercent < 100) {
            $maxPercent = 100;
        } else {
            $maxPercent += 10;
        }
        
        $data['months'] = $months;
        $data['legend'] = $legend;
        $data['prevYear'] = $prevYear;
        $data['curYear'] = $curYear;
        $data['maxPerson'] = $maxPerson;
        $data['maxPercent'] = $maxPercent;
        $data['prevPersons'] = $prevPersons;
        $data['curPersons'] = $curPersons;
        $data['percent'] = $percent;

        return $data;

    }


    private function getYears($yearId)
    {
        $nowYearId = date('Y');
        $curYearId = $yearId;
        $prevYearId = $curYearId - 1;
        // 如果查的事今年的,按实际今年过了几个月查对应去年的月份
        $curMonths = [];
        $prevMonths = [];
        $monthTotal = 12;
        // 如果查的是当年 
        if ($nowYearId == $yearId) {
            $monthTotal = intval(date('m'));
        }
        for ($m = 1; $m <= $monthTotal; $m++) {
            $mm = $m;
            if ($m < 10) {
                $mm = '0' . $m;
            }
            $curMonths[] = $curYearId . $mm;
            $prevMonths[] = $prevYearId . $mm;
        }

        return [$curMonths, $prevMonths];
    }

}
